﻿using System;
using System.Windows.Data;

namespace VNet.VisiSuite.VisiCentral.Common.Converters
{
    class BooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return CompareValueWithRequiredValueToBeChecked(value, parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return CompareValueWithRequiredValueToBeChecked(value, parameter);
        }

        private bool CompareValueWithRequiredValueToBeChecked(object value, object parameterValue)
        {
            bool? convertedValue = ConvertObjectToBool(value);
            bool? convertedParameter = ConvertObjectToBool(parameterValue);

            bool result = convertedValue == convertedParameter;

            return result;
        }

        private bool? ConvertObjectToBool(object parameter)
        {
            string stringResult = parameter == null ? null : parameter.ToString();
            bool? convertedResult;

            bool convertResultTest = false;
            if (stringResult != null && !bool.TryParse(stringResult, out convertResultTest))
            {
                throw new InvalidCastException(string.Format("Cannot convert {0} to a bool.", parameter));
            }

            convertedResult = stringResult == null ? (bool?)null : (bool?)convertResultTest;

            return convertedResult;
        }
    }
}
